<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>根据图片变化背景颜色</title>
  <link rel="stylesheet" href="./index.css">
</head>
<body>
  <div class="root">
    <div class="grid">
      <div class="item">
        <img class="img" crossorigin="anonymous" src="https://picsum.photos/800/800?r=1" alt="" onmouseenter="handleMouseEnter(1)" onmouseleave="handleMouseLeave(1)">
      </div>
      <div class="item">
        <img class="img" crossorigin="anonymous"src="https://picsum.photos/800/800?r=2" alt="" onmouseenter="handleMouseEnter(2)" onmouseleave="handleMouseLeave(2)">
      </div>
    </div>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/color-thief/2.3.0/color-thief.umd.js"></script>
  <script>
      const colorThief = new ColorThief();

      const handleMouseEnter = async (index) => {
        const img = document.querySelector(`.item:nth-child(${index}) img`);
        const colorList = await colorThief.getPalette(img, 3);
        const [ c1, c2, c3 ] = colorList.map(c => `rgb(${c[0]}, ${c[1]}, ${c[2]})`);
        document.body.style.backgroundImage = `linear-gradient(${c1}, ${c2}, ${c3})`;
      }

      const handleMouseLeave = () => {
        document.body.style.backgroundImage = '';
      }
  </script>
</body>
</html>
